<template>
  <div id="zabbix-alerts-page" class="zabbix-alerts-container ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <div class="content-wrapper">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1><i class="fa fa-bell"></i> 告警管理</h1>
            <p>监控告警管理和通知配置</p>
          </div>
          <div class="action-section">
            <button @click="refreshData" class="glass-button refresh-button" :loading="loading">
              <i class="fa fa-refresh"></i>
              刷新数据
            </button>
            <button @click="showCreateAlert" class="glass-button add-button">
              <i class="fa fa-plus"></i>
              创建规则
            </button>
            <button @click="showChart" class="glass-button chart-button">
              <i class="fa fa-bar-chart"></i>
              统计图表
            </button>
            <el-dropdown @command="handleTestSSE" trigger="click">
              <button class="glass-button test-button">
                <i class="fa fa-rocket"></i>
                SSE测试
                <i class="fa fa-caret-down"></i>
              </button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="simple">简单推送测试</el-dropdown-item>
                  <el-dropdown-item command="real">真实告警测试</el-dropdown-item>
                  <el-dropdown-item command="notification">通知渠道测试</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- SSE通知渠道配置按钮 -->
            <button class="glass-button config-button" @click="showSSEChannelConfig = true">
              <i class="fa fa-cog"></i>
              SSE通知配置
            </button>
          </div>
        </div>
      </div>

      <!-- 告警统计 -->
      <div class="stats-grid">
        <div class="stat-card glass-effect">
          <div class="stat-icon critical">
            <i class="fa fa-exclamation-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.critical_alerts || 0 }}</div>
            <div class="stat-label">紧急告警</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon high">
            <i class="fa fa-exclamation-triangle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.high_alerts || 0 }}</div>
            <div class="stat-label">严重告警</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon medium">
            <i class="fa fa-exclamation"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.medium_alerts || 0 }}</div>
            <div class="stat-label">一般告警</div>
          </div>
        </div>

        <div class="stat-card glass-effect">
          <div class="stat-icon low">
            <i class="fa fa-info-circle"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.low_alerts || 0 }}</div>
            <div class="stat-label">轻微告警</div>
          </div>
        </div>
      </div>

      <!-- 告警列表 -->
      <div class="alerts-section glass-effect">
        <div class="section-header">
          <h3><i class="fa fa-list"></i> 活跃告警</h3>
          <div class="filter-controls">
            <el-select v-model="filterSeverity" placeholder="严重级别" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="紧急" value="critical" />
              <el-option label="严重" value="high" />
              <el-option label="一般" value="medium" />
              <el-option label="轻微" value="low" />
            </el-select>
            <el-select v-model="filterStatus" placeholder="状态筛选" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="活跃" value="active" />
              <el-option label="已确认" value="acknowledged" />
              <el-option label="已解决" value="resolved" />
            </el-select>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索告警标题"
              style="width: 200px;"
              clearable
            >
              <template #prefix>
                <i class="fa fa-search"></i>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 批量操作栏 -->
        <div v-if="selectedAlerts.length > 0" class="batch-actions glass-effect">
          <div class="batch-info">
            <span>已选择 {{ selectedAlerts.length }} 个告警</span>
          </div>
          <div class="batch-buttons">
            <button @click="batchAcknowledge" class="action-btn acknowledge">
              <i class="fa fa-check"></i>
              批量确认
            </button>
            <button @click="batchResolve" class="action-btn resolve">
              <i class="fa fa-check-circle"></i>
              批量解决
            </button>
            <button @click="clearSelection" class="action-btn">
              <i class="fa fa-times"></i>
              取消选择
            </button>
          </div>
        </div>

        <div class="alerts-list">
          <div
            v-for="alert in paginatedAlerts"
            :key="alert.id"
            class="alert-card glass-effect"
            :class="getSeverityClass(alert.severity)"
          >
            <!-- 添加复选框 -->
            <div class="alert-checkbox">
              <el-checkbox
                v-model="selectedAlerts"
                :value="alert.id"
                @change="handleAlertSelection"
              />
            </div>
            <div class="alert-header">
              <div class="alert-info">
                <h4>{{ alert.title }}</h4>
                <span class="alert-host">{{ alert.host_info?.hostname || '未知主机' }}</span>
              </div>
              <div class="alert-meta">
                <span class="severity-badge" :class="getSeverityClass(alert.severity)">
                  {{ getSeverityText(alert.severity) }}
                </span>
                <span class="status-badge" :class="getStatusClass(alert.status)">
                  {{ getStatusText(alert.status) }}
                </span>
              </div>
            </div>

            <div class="alert-description" v-if="alert.description">
              {{ alert.description }}
            </div>

            <div class="alert-details">
              <div class="detail-item">
                <span class="label">触发时间:</span>
                <span class="value">{{ formatTime(alert.event_time) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">Zabbix服务器:</span>
                <span class="value">{{ alert.zabbix_server_name }}</span>
              </div>
              <div class="detail-item" v-if="alert.acknowledged_time">
                <span class="label">确认时间:</span>
                <span class="value">{{ formatTime(alert.acknowledged_time) }}</span>
              </div>
              <div class="detail-item" v-if="alert.acknowledged_by_name">
                <span class="label">确认人:</span>
                <span class="value">{{ alert.acknowledged_by_name }}</span>
              </div>
            </div>

            <div class="alert-actions">
              <button
                v-if="alert.status === 'active'"
                @click="acknowledgeAlert(alert)"
                class="action-btn acknowledge"
              >
                <i class="fa fa-check"></i>
                确认
              </button>
              <button
                v-if="alert.status !== 'resolved'"
                @click="resolveAlert(alert)"
                class="action-btn resolve"
              >
                <i class="fa fa-check-circle"></i>
                解决
              </button>
              <button @click="showAlertDetail(alert)" class="action-btn">
                <i class="fa fa-eye"></i>
                详情
              </button>
              <button
                @click="deleteAlert(alert)"
                class="action-btn delete"
                title="删除告警"
              >
                <i class="fa fa-trash"></i>
                删除
              </button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="filteredAlerts.length > 0" class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredAlerts.length"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 空状态 -->
        <div v-if="filteredAlerts.length === 0" class="empty-state">
          <i class="fa fa-bell-slash"></i>
          <h3>暂无告警数据</h3>
          <p>当前没有符合条件的告警信息</p>
        </div>
      </div>

      <!-- 通知配置管理 -->
      <div class="notification-section glass-effect">
        <div class="section-header">
          <h3><i class="fa fa-bell"></i> 通知配置</h3>
          <div class="header-actions">
            <el-dropdown @command="handleAddNotification" trigger="click">
              <button class="glass-button add-button">
                <i class="fa fa-plus"></i>
                添加通知渠道
                <i class="fa fa-caret-down"></i>
              </button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="email">
                    <i class="fa fa-envelope"></i> 邮件通知
                  </el-dropdown-item>
                  <el-dropdown-item command="wechat">
                    <i class="fa fa-weixin"></i> 企业微信
                  </el-dropdown-item>
                  <el-dropdown-item command="dingtalk">
                    <i class="fa fa-bell"></i> 钉钉通知
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>

        <div class="notification-configs-table">
          <!-- 表格头部 -->
          <div class="table-header">
            <div class="header-cell name">配置名称</div>
            <div class="header-cell type">通知类型</div>
            <div class="header-cell config">配置信息</div>
            <div class="header-cell recipients">接收对象</div>
            <div class="header-cell status">状态</div>
            <div class="header-cell actions">操作</div>
          </div>

          <!-- 表格内容 -->
          <div
            v-for="channel in notificationChannels"
            :key="channel.id"
            class="table-row glass-effect"
          >
            <div class="table-cell name">
              <span class="config-name">{{ channel.name }}</span>
            </div>
            <div class="table-cell type">
              <span :class="['type-badge', `type-${channel.channel_type}`]">
                <i :class="getChannelIcon(channel.channel_type)"></i>
                {{ getChannelTypeName(channel.channel_type) }}
              </span>
            </div>
            <div class="table-cell config">
              <div class="config-info">
                <template v-if="channel.channel_type === 'email'">
                  <span>{{ channel.config.smtp_server }}:{{ channel.config.smtp_port }}</span>
                </template>
                <template v-else-if="channel.channel_type === 'wechat'">
                  <span>企业微信群机器人</span>
                </template>
                <template v-else-if="channel.channel_type === 'dingtalk'">
                  <span>钉钉群机器人</span>
                </template>
                <template v-else>
                  <span>{{ channel.channel_type }}</span>
                </template>
              </div>
            </div>
            <div class="table-cell recipients">
              <div class="recipients-container">
                <template v-if="channel.channel_type === 'email'">
                  <template v-if="channel.config.recipients && channel.config.recipients.length > 0">
                    <div
                      v-for="(email, index) in channel.config.recipients"
                      :key="index"
                      :class="['recipient-tag', `recipient-${index % 6}`]"
                    >
                      {{ email }}
                    </div>
                  </template>
                  <span v-else class="no-recipients">未配置收件人</span>
                </template>
                <template v-else-if="channel.channel_type === 'wechat'">
                  <template v-if="channel.config.mentioned_list && channel.config.mentioned_list.length > 0">
                    <div
                      v-for="(user, index) in channel.config.mentioned_list"
                      :key="index"
                      :class="['recipient-tag', `recipient-${index % 6}`]"
                    >
                      @{{ user }}
                    </div>
                  </template>
                  <span v-else class="no-recipients">全员</span>
                </template>
                <template v-else-if="channel.channel_type === 'dingtalk'">
                  <template v-if="channel.config.at_all">
                    <span class="no-recipients">@所有人</span>
                  </template>
                  <template v-else-if="channel.config.at_mobiles && channel.config.at_mobiles.length > 0">
                    <div
                      v-for="(mobile, index) in channel.config.at_mobiles"
                      :key="index"
                      :class="['recipient-tag', `recipient-${index % 6}`]"
                    >
                      {{ mobile }}
                    </div>
                  </template>
                  <span v-else class="no-recipients">全员</span>
                </template>
              </div>
            </div>
            <div class="table-cell status">
              <el-switch
                v-model="channel.is_active"
                @change="toggleNotificationChannel(channel)"
                active-color="#22c55e"
                inactive-color="#6b7280"
                size="small"
              />
            </div>
            <div class="table-cell actions">
              <div class="action-buttons">
                <!-- 测试、编辑、删除按钮在一行 -->
                <div class="main-actions">
                  <button @click="testNotificationChannel(channel)" class="action-btn test" :disabled="testingChannel === channel.id">
                    <i class="fa fa-paper-plane"></i>
                    {{ testingChannel === channel.id ? '测试中...' : '测试' }}
                  </button>
                  <button @click="editNotificationChannel(channel)" class="action-btn edit">
                    <i class="fa fa-edit"></i>
                    编辑
                  </button>
                  <button @click="deleteNotificationChannel(channel)" class="action-btn delete">
                    <i class="fa fa-trash"></i>
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="notificationChannels.length === 0" class="empty-state">
          <i class="fa fa-bell-o"></i>
          <h3>暂无通知渠道</h3>
          <p>请添加通知渠道以启用告警通知功能</p>
        </div>
      </div>

      <!-- 告警规则管理 -->
      <div class="rules-section glass-effect">
        <div class="section-header">
          <h3><i class="fa fa-cogs"></i> 告警规则</h3>
          <button @click="showCreateRule" class="glass-button add-button">
            <i class="fa fa-plus"></i>
            添加规则
          </button>
        </div>

        <div class="rules-list">
          <div
            v-for="rule in alertRules"
            :key="rule.id"
            class="rule-card glass-effect"
          >
            <div class="rule-header">
              <div class="rule-info">
                <h4>{{ rule.name }}</h4>
                <span class="rule-metric">{{ rule.metric_name }}</span>
              </div>
              <div class="rule-status">
                <el-switch
                  v-model="rule.is_active"
                  @change="toggleRule(rule)"
                  active-color="#22c55e"
                  inactive-color="#6b7280"
                />
              </div>
            </div>

            <div class="rule-condition">
              <span class="condition-text">
                当 {{ rule.metric_name }} {{ rule.condition }} {{ rule.threshold_value }}
                持续 {{ rule.duration }}秒 时触发 {{ getSeverityText(rule.severity) }} 告警
              </span>
            </div>

            <div class="rule-actions">
              <button @click="editRule(rule)" class="action-btn">
                <i class="fa fa-edit"></i>
                编辑
              </button>
              <button @click="testRule(rule)" class="action-btn">
                <i class="fa fa-play"></i>
                测试
              </button>
              <button @click="deleteRule(rule)" class="action-btn delete">
                <i class="fa fa-trash"></i>
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 邮件配置对话框 -->
  <el-dialog
    v-model="emailConfigDialog.visible"
    :title="emailConfigDialog.isEdit ? '编辑邮件配置' : '添加邮件配置'"
    width="600px"
    class="glass-dialog"
  >
    <el-form
      ref="emailConfigFormRef"
      :model="emailConfigDialog.form"
      :rules="emailConfigRules"
      label-width="120px"
    >
      <el-form-item label="配置名称" prop="name">
        <el-input v-model="emailConfigDialog.form.name" placeholder="请输入配置名称" />
      </el-form-item>

      <el-form-item label="SMTP服务器" prop="smtp_server">
        <el-input v-model="emailConfigDialog.form.smtp_server" placeholder="如: smtp.qq.com" />
      </el-form-item>

      <el-form-item label="SMTP端口" prop="smtp_port">
        <el-input-number v-model="emailConfigDialog.form.smtp_port" :min="1" :max="65535" />
      </el-form-item>

      <el-form-item label="用户名" prop="username">
        <el-input v-model="emailConfigDialog.form.username" placeholder="请输入邮箱用户名" />
      </el-form-item>

      <el-form-item label="密码/授权码" prop="password">
        <el-input
          v-model="emailConfigDialog.form.password"
          type="password"
          :placeholder="emailConfigDialog.isEdit ? '密码已保存，如需修改请重新输入' : '请输入邮箱密码或授权码'"
          show-password
        />
        <div v-if="emailConfigDialog.isEdit" class="form-tip">
          当前显示为占位符，如需修改密码请重新输入
        </div>
      </el-form-item>

      <el-form-item label="发件人邮箱" prop="from_email">
        <el-input v-model="emailConfigDialog.form.from_email" placeholder="请输入发件人邮箱" />
      </el-form-item>

      <el-form-item label="默认收件人" prop="default_recipients">
        <el-input
          v-model="emailConfigDialog.form.default_recipients"
          type="textarea"
          :rows="3"
          placeholder="请输入收件人邮箱，多个邮箱用逗号分隔&#10;例如: admin@company.com, ops@company.com"
        />
      </el-form-item>

      <el-form-item label="加密方式">
        <el-radio-group v-model="emailConfigDialog.form.encryption">
          <el-radio value="tls">TLS</el-radio>
          <el-radio value="ssl">SSL</el-radio>
          <el-radio value="none">无加密</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="设为默认">
        <el-switch v-model="emailConfigDialog.form.is_default" />
      </el-form-item>

      <el-form-item label="启用配置">
        <el-switch v-model="emailConfigDialog.form.is_active" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emailConfigDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveEmailConfig" :loading="emailConfigDialog.loading">
          {{ emailConfigDialog.isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 通知渠道对话框 -->
  <el-dialog
    v-model="notificationChannelDialog.visible"
    :title="notificationChannelDialog.isEdit ? '编辑通知渠道' : '添加通知渠道'"
    width="600px"
    class="glass-dialog"
  >
    <el-form
      ref="notificationChannelFormRef"
      :model="notificationChannelDialog.form"
      label-width="120px"
      class="glass-form"
    >
      <el-form-item label="渠道名称" prop="name" :rules="[{ required: true, message: '请输入渠道名称', trigger: 'blur' }]">
        <el-input v-model="notificationChannelDialog.form.name" placeholder="请输入渠道名称" />
      </el-form-item>

      <el-form-item label="通知类型">
        <el-select v-model="notificationChannelDialog.form.channel_type" :disabled="notificationChannelDialog.isEdit">
          <el-option label="邮件通知" value="email" />
          <el-option label="企业微信" value="wechat" />
          <el-option label="钉钉通知" value="dingtalk" />
        </el-select>
      </el-form-item>

      <!-- 邮件配置 -->
      <template v-if="notificationChannelDialog.form.channel_type === 'email'">
        <el-form-item label="SMTP服务器" prop="config.smtp_server" :rules="[{ required: true, message: '请输入SMTP服务器', trigger: 'blur' }]">
          <el-input v-model="notificationChannelDialog.form.config.smtp_server" placeholder="如：smtp.qq.com" />
        </el-form-item>
        <el-form-item label="SMTP端口" prop="config.smtp_port" :rules="[{ required: true, message: '请输入SMTP端口', trigger: 'blur' }]">
          <el-input-number v-model="notificationChannelDialog.form.config.smtp_port" :min="1" :max="65535" />
        </el-form-item>
        <el-form-item label="用户名" prop="config.username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="notificationChannelDialog.form.config.username" placeholder="邮箱账号" />
        </el-form-item>
        <el-form-item label="密码" :prop="notificationChannelDialog.isEdit ? '' : 'config.password'" :rules="notificationChannelDialog.isEdit ? [] : [{ required: true, message: '请输入密码', trigger: 'blur' }]">
          <el-input
            v-model="notificationChannelDialog.form.config.password"
            type="password"
            show-password
            :placeholder="notificationChannelDialog.isEdit ? '留空则不修改密码' : '邮箱密码或授权码'"
          />
        </el-form-item>
        <el-form-item label="发件人邮箱" prop="config.from_email" :rules="[{ required: true, message: '请输入发件人邮箱', trigger: 'blur' }, { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }]">
          <el-input v-model="notificationChannelDialog.form.config.from_email" placeholder="发件人邮箱地址" />
        </el-form-item>
        <el-form-item label="收件人">
          <el-input
            v-model="emailRecipients"
            placeholder="多个邮箱用逗号分隔，如：user1@example.com,user2@example.com"
            @blur="updateEmailRecipients"
          />
          <div class="form-help">可选：默认收件人列表，留空则需要在发送时指定</div>
        </el-form-item>
        <el-form-item label="加密方式">
          <el-select v-model="notificationChannelDialog.form.config.encryption">
            <el-option label="TLS" value="tls" />
            <el-option label="SSL" value="ssl" />
            <el-option label="无加密" value="none" />
          </el-select>
        </el-form-item>
      </template>

      <!-- 企业微信配置 -->
      <template v-if="notificationChannelDialog.form.channel_type === 'wechat'">
        <el-form-item label="Webhook URL" prop="config.webhook_url" :rules="[{ required: true, message: '请输入Webhook URL', trigger: 'blur' }]">
          <el-input
            v-model="notificationChannelDialog.form.config.webhook_url"
            placeholder="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxx"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="@用户列表">
          <el-input
            v-model="mentionedUsers"
            placeholder="多个用户用逗号分隔，如：user1,user2"
            @blur="updateMentionedList"
          />
          <div class="form-help">可选：指定要@的用户，留空则不@任何人</div>
        </el-form-item>
      </template>

      <!-- 钉钉配置 -->
      <template v-if="notificationChannelDialog.form.channel_type === 'dingtalk'">
        <el-form-item label="Webhook URL" prop="config.webhook_url" :rules="[{ required: true, message: '请输入Webhook URL', trigger: 'blur' }]">
          <el-input
            v-model="notificationChannelDialog.form.config.webhook_url"
            placeholder="https://oapi.dingtalk.com/robot/send?access_token=xxx"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="签名密钥">
          <el-input
            v-model="notificationChannelDialog.form.config.secret"
            placeholder="可选：钉钉机器人的签名密钥"
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="安全关键词">
          <el-input
            v-model="notificationChannelDialog.form.config.keyword"
            placeholder="请输入钉钉机器人安全关键词，如：devops"
          />
          <div class="form-help">关键词将自动添加到消息开头以通过安全验证</div>
        </el-form-item>
        <el-form-item label="@手机号">
          <el-input
            v-model="atMobiles"
            placeholder="多个手机号用逗号分隔，如：13800138000,13900139000"
            @blur="updateAtMobiles"
          />
          <div class="form-help">可选：指定要@的手机号，留空则不@任何人</div>
        </el-form-item>
        <el-form-item label="@所有人">
          <el-switch v-model="notificationChannelDialog.form.config.at_all" />
        </el-form-item>
      </template>

      <el-form-item label="启用状态">
        <el-switch v-model="notificationChannelDialog.form.is_active" />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="notificationChannelDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveNotificationChannel" :loading="notificationChannelDialog.loading">
          {{ notificationChannelDialog.isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 告警详情对话框 -->
  <el-dialog
    v-model="alertDetailDialog.visible"
    title="告警详情"
    width="800px"
    class="glass-dialog"
  >
    <div v-if="alertDetailDialog.alert" class="alert-detail-content">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h4><i class="fa fa-info-circle"></i> 基本信息</h4>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label">告警标题:</span>
            <span class="value">{{ alertDetailDialog.alert.title }}</span>
          </div>
          <div class="detail-item">
            <span class="label">主机名:</span>
            <span class="value">{{ alertDetailDialog.alert.hostname }}</span>
          </div>
          <div class="detail-item">
            <span class="label">严重级别:</span>
            <span :class="['value', 'severity-badge', getSeverityClass(alertDetailDialog.alert.severity)]">
              {{ getSeverityText(alertDetailDialog.alert.severity) }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">状态:</span>
            <span :class="['value', 'status-badge', getStatusClass(alertDetailDialog.alert.status)]">
              {{ getStatusText(alertDetailDialog.alert.status) }}
            </span>
          </div>
          <div class="detail-item">
            <span class="label">触发时间:</span>
            <span class="value">{{ formatTime(alertDetailDialog.alert.event_time) }}</span>
          </div>
          <div class="detail-item">
            <span class="label">Zabbix服务器:</span>
            <span class="value">{{ alertDetailDialog.alert.zabbix_server_name }}</span>
          </div>
        </div>
      </div>

      <!-- 告警描述 -->
      <div class="detail-section" v-if="alertDetailDialog.alert.description">
        <h4><i class="fa fa-file-text"></i> 告警描述</h4>
        <div class="description-content">
          {{ alertDetailDialog.alert.description }}
        </div>
      </div>

      <!-- 确认信息 -->
      <div class="detail-section" v-if="alertDetailDialog.alert.acknowledged_time">
        <h4><i class="fa fa-check"></i> 确认信息</h4>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label">确认时间:</span>
            <span class="value">{{ formatTime(alertDetailDialog.alert.acknowledged_time) }}</span>
          </div>
          <div class="detail-item" v-if="alertDetailDialog.alert.acknowledged_by_name">
            <span class="label">确认人:</span>
            <span class="value">{{ alertDetailDialog.alert.acknowledged_by_name }}</span>
          </div>
          <div class="detail-item" v-if="alertDetailDialog.alert.acknowledged_comment">
            <span class="label">确认备注:</span>
            <span class="value">{{ alertDetailDialog.alert.acknowledged_comment }}</span>
          </div>
        </div>
      </div>

      <!-- 原始数据 -->
      <div class="detail-section">
        <h4><i class="fa fa-code"></i> 原始数据</h4>
        <div class="json-content">
          <pre>{{ JSON.stringify(alertDetailDialog.alert, null, 2) }}</pre>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="alertDetailDialog.visible = false">关闭</el-button>
        <el-button
          v-if="alertDetailDialog.alert && alertDetailDialog.alert.status === 'active'"
          type="warning"
          @click="acknowledgeAlertFromDetail"
        >
          确认告警
        </el-button>
        <el-button
          v-if="alertDetailDialog.alert && alertDetailDialog.alert.status !== 'resolved'"
          type="success"
          @click="resolveAlertFromDetail"
        >
          解决告警
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 统计图表对话框 -->
  <el-dialog
    v-model="chartDialog.visible"
    title="告警统计图表"
    width="900px"
    class="glass-dialog"
  >
    <div class="chart-container">
      <div ref="alertChart" style="width: 100%; height: 400px;"></div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="chartDialog.visible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 告警规则对话框 -->
  <el-dialog
    v-model="alertRuleDialog.visible"
    :title="alertRuleDialog.title"
    width="700px"
    class="glass-dialog"
  >
    <el-form :model="alertRuleForm" label-width="120px" class="glass-form">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="规则名称" required>
            <el-input v-model="alertRuleForm.name" placeholder="请输入规则名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="严重级别" required>
            <el-select v-model="alertRuleForm.severity" placeholder="请选择严重级别" style="width: 100%">
              <el-option
                v-for="option in severityOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="规则描述">
        <el-input
          v-model="alertRuleForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入规则描述"
        />
      </el-form-item>

      <el-form-item label="Zabbix服务器" required>
        <el-select
          v-model="alertRuleForm.zabbix_server"
          style="width: 100%"
          placeholder="请选择Zabbix服务器"
          @change="onZabbixServerChange"
        >
          <el-option
            v-for="server in zabbixServers"
            :key="server.id"
            :label="server.name"
            :value="server.id"
          />
        </el-select>
        <div class="form-help" v-if="zabbixServers.length === 0">
          暂无可用的Zabbix服务器
        </div>
        <div class="form-help" v-else>
          共 {{ zabbixServers.length }} 个Zabbix服务器
        </div>
      </el-form-item>

      <el-form-item label="监控模板" required>
        <el-autocomplete
          v-model="templateSearchQuery"
          style="width: 100%"
          placeholder="输入模板名称进行搜索..."
          :fetch-suggestions="searchTemplates"
          :loading="templatesLoading"
          @select="onTemplateSelect"
          clearable
          :debounce="500"
        >
          <template #default="{ item }">
            <div class="template-item">
              <div class="template-name">{{ item.name }}</div>
            </div>
          </template>
        </el-autocomplete>
        <div v-if="selectedTemplate" class="selected-template">
          <el-tag type="success" closable @close="clearSelectedTemplate">
            {{ selectedTemplate.name }}
          </el-tag>
        </div>
      </el-form-item>

      <el-form-item label="监控项" required>
        <el-select
          v-model="alertRuleForm.metric_name"
          style="width: 100%"
          placeholder="请选择监控项"
          :loading="itemsLoading"
        >
          <el-option
            v-for="item in metricOptions"
            :key="item.key_"
            :label="`${item.name} (${item.key_})`"
            :value="item.key_"
          />
        </el-select>
        <div class="form-help">
          从Zabbix服务器获取的真实监控项列表
        </div>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="条件" required>
            <el-select
              v-model="alertRuleForm.condition"
              style="width: 100%; min-width: 120px;"
              placeholder="选择条件"
              popper-class="condition-select-dropdown"
            >
              <el-option
                v-for="option in conditionOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="阈值" required>
            <el-input
              v-model="alertRuleForm.threshold_value"
              placeholder="请输入阈值"
              class="threshold-input"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="持续时间(秒)">
            <el-input-number
              v-model="alertRuleForm.duration"
              :min="60"
              :step="60"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态">
            <el-switch
              v-model="alertRuleForm.is_active"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="启用通知">
        <el-switch
          v-model="alertRuleForm.enable_notification"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

      <el-form-item label="通知渠道" v-if="alertRuleForm.enable_notification">
        <el-select
          v-model="alertRuleForm.notification_channels"
          multiple
          placeholder="请选择通知渠道"
          style="width: 100%"
          collapse-tags
          collapse-tags-tooltip
        >
          <el-option
            v-for="channel in notificationChannels.filter(c => c.is_active)"
            :key="channel.id"
            :label="channel.name"
            :value="channel.id"
          >
            <span style="float: left">{{ channel.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ channel.channel_type === 'email' ? '邮件' :
                 channel.channel_type === 'wechat' ? '企业微信' :
                 channel.channel_type === 'dingtalk' ? '钉钉' :
                 channel.channel_type === 'webhook' ? 'Webhook' :
                 channel.channel_type }}
            </span>
          </el-option>
          <!-- 调试信息 -->
          <div v-if="notificationChannels.filter(c => c.is_active).length === 0" style="padding: 10px; color: #999;">
            没有找到可用的通知渠道
          </div>
        </el-select>
        <div class="form-tip">
          可选择多个通知渠道，告警时会同时发送到所有选中的渠道
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="alertRuleDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="saveAlertRule">
          {{ alertRuleDialog.isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- SSE通知渠道配置对话框 -->
  <el-dialog
    v-model="showSSEChannelConfig"
    title="SSE通知渠道配置"
    width="600px"
    class="glass-dialog"
  >
    <div class="sse-config-content">
      <div class="config-description">
        <p>配置SSE实时告警推送使用的通知渠道。选中的渠道将在收到SSE告警时自动发送通知。</p>
      </div>

      <div class="channel-selection">
        <h4>选择通知渠道</h4>
        <div class="channel-list">
          <div
            v-for="channel in notificationChannels.filter(c => c.is_active)"
            :key="channel.id"
            class="channel-item"
            :class="{ 'selected': sseSelectedChannels.includes(channel.id) }"
            @click="toggleSSEChannel(channel.id)"
          >
            <div class="channel-info">
              <div class="channel-name">
                <i :class="getChannelIcon(channel.channel_type)"></i>
                {{ channel.name }}
              </div>
              <div class="channel-type">{{ channel.channel_type_display }}</div>
              <div class="channel-status" :class="{ 'active': channel.is_active }">
                {{ channel.is_active ? '启用' : '禁用' }}
              </div>
            </div>
            <div class="channel-checkbox">
              <i class="fa fa-check" v-if="sseSelectedChannels.includes(channel.id)"></i>
            </div>
          </div>
        </div>
      </div>

      <div class="config-actions">
        <el-button @click="testSSENotification" type="primary" :loading="testingSSENotification">
          <i class="fa fa-paper-plane"></i>
          测试选中渠道
        </el-button>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showSSEChannelConfig = false">取消</el-button>
        <el-button type="primary" @click="saveSSEChannelConfig" :loading="savingSSEConfig">
          保存配置
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { monitoringApi } from '@/api/monitoring'
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { computed, nextTick, onMounted, onUnmounted, reactive, ref } from 'vue'

// 响应式数据
const loading = ref(false)
const filterSeverity = ref('')
const filterStatus = ref('')
const searchKeyword = ref('')

// SSE通知配置相关
const showSSEChannelConfig = ref(false)
const sseSelectedChannels = ref([])
const testingSSENotification = ref(false)
const savingSSEConfig = ref(false)

// 统计数据
const statistics = reactive({
  critical_alerts: 0,
  high_alerts: 0,
  medium_alerts: 0,
  low_alerts: 0
})

// 告警和规则列表
const alerts = ref([])

// 分页相关
const currentPage = ref(1)
const pageSize = ref(20)

// 批量操作相关
const selectedAlerts = ref([])

// 告警详情对话框
const alertDetailDialog = reactive({
  visible: false,
  alert: null
})

// 统计图表对话框
const chartDialog = reactive({
  visible: false
})

// 图表引用
const alertChart = ref(null)
const emailConfigs = ref([])
const notificationChannels = ref([])
const alertRuleNotificationChannels = ref([]) // 告警规则专用通知渠道（只包含真正的通知渠道）
const testingConfig = ref(null)
const testingChannel = ref(null)

// 邮件配置对话框
const emailConfigDialog = reactive({
  visible: false,
  isEdit: false,
  loading: false,
  form: {
    name: '',
    smtp_server: '',
    smtp_port: 587,
    username: '',
    password: '',
    from_email: '',
    default_recipients: '',
    encryption: 'tls',
    is_default: false,
    is_active: true
  }
})

const emailConfigFormRef = ref()

const emailConfigRules = {
  name: [
    { required: true, message: '请输入配置名称', trigger: 'blur' }
  ],
  smtp_server: [
    { required: true, message: '请输入SMTP服务器', trigger: 'blur' }
  ],
  smtp_port: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    {
      required: false, // 编辑模式下不要求必填
      message: '请输入密码或授权码',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 如果是编辑模式且值是占位符，则验证通过
        if (emailConfigDialog.isEdit && value === '••••••••••••') {
          callback()
        } else if (!emailConfigDialog.isEdit && !value) {
          // 只有在创建模式下才要求必填
          callback(new Error('请输入密码或授权码'))
        } else {
          callback()
        }
      }
    }
  ],
  from_email: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

// 通知渠道对话框
const notificationChannelDialog = reactive({
  visible: false,
  isEdit: false,
  loading: false,
  channelType: 'email',
  form: {
    name: '',
    channel_type: 'email',
    config: {},
    is_active: true
  }
})

const notificationChannelFormRef = ref()

// 辅助变量用于表单处理
const mentionedUsers = ref('')
const atMobiles = ref('')
const emailRecipients = ref('')

// 计算属性
const filteredAlerts = computed(() => {
  let filtered = alerts.value

  // 严重级别筛选
  if (filterSeverity.value) {
    filtered = filtered.filter(alert => alert.severity === filterSeverity.value)
  }

  // 状态筛选
  if (filterStatus.value) {
    filtered = filtered.filter(alert => alert.status === filterStatus.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(alert =>
      alert.title.toLowerCase().includes(keyword) ||
      (alert.description && alert.description.toLowerCase().includes(keyword))
    )
  }

  return filtered
})

// 分页后的告警列表
const paginatedAlerts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAlerts.value.slice(start, end)
})

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 批量操作方法
const handleAlertSelection = () => {
  // 复选框变化处理
}

const clearSelection = () => {
  selectedAlerts.value = []
}

const batchAcknowledge = async () => {
  if (selectedAlerts.value.length === 0) {
    ElMessage.warning('请选择要确认的告警')
    return
  }

  try {
    const comment = await ElMessageBox.prompt('请输入确认备注', '批量确认告警', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '备注不能为空'
    })

    for (const alertId of selectedAlerts.value) {
      await monitoringApi.acknowledgeAlert(alertId, {
        message: comment.value
      })
    }

    ElMessage.success('批量确认成功')
    clearSelection()
    await loadAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量确认失败: ' + (error.message || error))
    }
  }
}

const batchResolve = async () => {
  if (selectedAlerts.value.length === 0) {
    ElMessage.warning('请选择要解决的告警')
    return
  }

  try {
    await ElMessageBox.confirm('确定要批量解决选中的告警吗？', '批量解决告警', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    for (const alertId of selectedAlerts.value) {
      await monitoringApi.resolveAlert({
        alert_id: alertId
      })
    }

    ElMessage.success('批量解决成功')
    clearSelection()
    await loadAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量解决失败: ' + (error.message || error))
    }
  }
}

// 告警详情方法
const showAlertDetail = (alert) => {
  alertDetailDialog.alert = alert
  alertDetailDialog.visible = true
}

const acknowledgeAlertFromDetail = async () => {
  try {
    const comment = await ElMessageBox.prompt('请输入确认备注', '确认告警', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '备注不能为空'
    })

    await monitoringApi.acknowledgeAlert(alertDetailDialog.alert.id, {
      message: comment.value
    })

    ElMessage.success('告警确认成功')
    alertDetailDialog.visible = false
    await loadAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('确认失败: ' + (error.message || error))
    }
  }
}

const resolveAlertFromDetail = async () => {
  try {
    await ElMessageBox.confirm('确定要解决这个告警吗？', '解决告警', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await monitoringApi.resolveAlert({
      alert_id: alertDetailDialog.alert.id
    })

    ElMessage.success('告警解决成功')
    alertDetailDialog.visible = false
    await loadAlerts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('解决失败: ' + (error.message || error))
    }
  }
}

// 统计图表方法
const showChart = () => {
  chartDialog.visible = true
  nextTick(() => {
    initChart()
  })
}

const initChart = () => {
  if (!alertChart.value) return

  const chart = echarts.init(alertChart.value)

  // 按严重级别统计
  const severityStats = {
    disaster: 0,
    high: 0,
    average: 0,
    warning: 0,
    information: 0,
    not_classified: 0
  }

  alerts.value.forEach(alert => {
    if (severityStats.hasOwnProperty(alert.severity)) {
      severityStats[alert.severity]++
    }
  })

  const option = {
    title: {
      text: '告警统计',
      left: 'center',
      textStyle: {
        color: '#fff'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: '#fff'
      }
    },
    series: [
      {
        name: '告警级别',
        type: 'pie',
        radius: '50%',
        data: [
          { value: severityStats.disaster, name: '灾难', itemStyle: { color: '#ff4757' } },
          { value: severityStats.high, name: '严重', itemStyle: { color: '#ff6b81' } },
          { value: severityStats.average, name: '一般', itemStyle: { color: '#ffa502' } },
          { value: severityStats.warning, name: '警告', itemStyle: { color: '#fffa65' } },
          { value: severityStats.information, name: '信息', itemStyle: { color: '#70a1ff' } },
          { value: severityStats.not_classified, name: '未分类', itemStyle: { color: '#747d8c' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ],
    backgroundColor: 'transparent'
  }

  chart.setOption(option)
}

// 方法
const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      loadAlerts(),
      loadAlertRules(),
      loadStatistics(),
      loadEmailConfigs(),
      loadNotificationChannels(),
      loadZabbixServers()  // 添加Zabbix服务器数据加载
    ])
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    loading.value = false
  }
}

const loadAlerts = async () => {
  try {
    const response = await monitoringApi.getAlerts()
    // 处理DRF标准分页响应格式
    if (response.data && response.data.results) {
      alerts.value = response.data.results || []
    } else if (response.data.success) {
      // 兼容旧格式
      alerts.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载告警列表失败:', error)
  }
}



const loadStatistics = async () => {
  try {
    const response = await monitoringApi.getOverview()
    if (response.data.success) {
      const data = response.data.data
      // 修正数据路径：alert_severity在monitoring对象下
      if (data.monitoring && data.monitoring.alert_severity) {
        const alertSeverity = data.monitoring.alert_severity
        statistics.critical_alerts = alertSeverity.critical || 0
        statistics.high_alerts = alertSeverity.high || 0
        statistics.medium_alerts = alertSeverity.medium || 0
        statistics.low_alerts = alertSeverity.low || 0
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const loadEmailConfigs = async () => {
  try {
    const response = await monitoringApi.getEmailConfigs()
    if (response.data.results) {
      emailConfigs.value = response.data.results
    }
  } catch (error) {
    console.error('加载邮件配置失败:', error)
  }
}

const loadNotificationChannels = async () => {
  try {
    console.log('🔄 开始加载通知渠道...')

    // 加载通知渠道（后端会自动同步邮件配置为通知渠道）
    const response = await monitoringApi.getNotificationChannels()
    console.log('📡 通知渠道API响应:', response.data)

    let channels = []
    if (response.data.results) {
      channels = response.data.results
      console.log('✅ 加载到通知渠道:', channels.length, '个')

      // 显示所有渠道的详细信息
      channels.forEach(channel => {
        console.log(`  📋 渠道: ${channel.name} (${channel.channel_type}) - ID: ${channel.id} - 激活: ${channel.is_active}`)
      })
    }

    notificationChannels.value = channels
  } catch (error) {
    console.error('❌ 加载通知渠道失败:', error)
  }
}

// 通知渠道相关方法
const handleAddNotification = (command) => {
  notificationChannelDialog.channelType = command
  notificationChannelDialog.form = {
    name: '',
    channel_type: command,
    config: getDefaultConfig(command),
    is_active: true
  }
  notificationChannelDialog.isEdit = false
  notificationChannelDialog.visible = true
}

const getDefaultConfig = (channelType) => {
  switch (channelType) {
    case 'email':
      return {
        smtp_server: '',
        smtp_port: 587,
        username: '',
        password: '',
        from_email: '',
        recipients: [],
        encryption: 'tls'
      }
    case 'wechat':
      return {
        webhook_url: '',
        mentioned_list: []
      }
    case 'dingtalk':
      return {
        webhook_url: '',
        secret: '',
        at_mobiles: [],
        at_all: false
      }
    default:
      return {}
  }
}

const getChannelIcon = (channelType) => {
  const icons = {
    email: 'fa fa-envelope',
    wechat: 'fa fa-weixin',
    dingtalk: 'fa fa-bell'
  }
  return icons[channelType] || 'fa fa-bell'
}

const getChannelTypeName = (channelType) => {
  const names = {
    email: '邮件通知',
    wechat: '企业微信',
    dingtalk: '钉钉通知'
  }
  return names[channelType] || channelType
}

const getSeverityClass = (severity) => {
  return `severity-${severity}`
}

const getSeverityText = (severity) => {
  const map = {
    critical: '紧急',
    high: '严重',
    medium: '一般',
    low: '轻微'
  }
  return map[severity] || severity
}

const getStatusClass = (status) => {
  return `status-${status}`
}

const getStatusText = (status) => {
  const map = {
    active: '活跃',
    acknowledged: '已确认',
    resolved: '已解决'
  }
  return map[status] || status
}

const formatTime = (timeString) => {
  if (!timeString) return '未知'
  const date = new Date(timeString)
  return date.toLocaleString('zh-CN')
}

const formatRecipients = (recipients) => {
  if (!recipients) return '未配置'
  const emails = recipients.split(',').map(email => email.trim()).filter(email => email)
  if (emails.length === 0) return '未配置'
  if (emails.length === 1) return emails[0]
  if (emails.length <= 3) return emails.join(', ')
  return `${emails.slice(0, 2).join(', ')} 等${emails.length}个邮箱`
}

// 通知渠道操作方法
const testNotificationChannel = async (channel) => {
  testingChannel.value = channel.id
  try {
    let response
    // 如果是邮件配置，使用邮件配置API
    if (channel._original_email_id) {
      response = await monitoringApi.testEmailConfig(channel._original_email_id)
    } else {
      response = await monitoringApi.testNotificationChannel(channel.id)
    }

    if (response.data.success) {
      ElMessage.success('测试通知发送成功')
    } else {
      ElMessage.error(response.data.message || '测试通知发送失败')
    }
  } catch (error) {
    console.error('测试通知渠道失败:', error)
    ElMessage.error('测试通知发送失败')
  } finally {
    testingChannel.value = null
  }
}

const editNotificationChannel = (channel) => {
  notificationChannelDialog.form = { ...channel }
  notificationChannelDialog.channelType = channel.channel_type
  notificationChannelDialog.isEdit = true

  // 设置辅助表单字段
  if (channel.channel_type === 'email' && channel.config.recipients) {
    emailRecipients.value = channel.config.recipients.join(',')
  } else {
    emailRecipients.value = ''
  }

  if (channel.channel_type === 'wechat' && channel.config.mentioned_list) {
    mentionedUsers.value = channel.config.mentioned_list.join(',')
  } else {
    mentionedUsers.value = ''
  }

  if (channel.channel_type === 'dingtalk' && channel.config.at_mobiles) {
    atMobiles.value = channel.config.at_mobiles.join(',')
  } else {
    atMobiles.value = ''
  }

  notificationChannelDialog.visible = true
}

const deleteNotificationChannel = async (channel) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除通知渠道 "${channel.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 如果是邮件配置，使用邮件配置API
    if (channel._original_email_id) {
      await monitoringApi.deleteEmailConfig(channel._original_email_id)
    } else {
      await monitoringApi.deleteNotificationChannel(channel.id)
    }

    ElMessage.success('删除成功')
    await loadNotificationChannels()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除通知渠道失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const toggleNotificationChannel = async (channel) => {
  try {
    // 如果是邮件配置，使用邮件配置API
    if (channel._original_email_id) {
      await monitoringApi.updateEmailConfig(channel._original_email_id, {
        is_active: channel.is_active
      })
    } else {
      await monitoringApi.updateNotificationChannel(channel.id, {
        is_active: channel.is_active
      })
    }
    ElMessage.success(channel.is_active ? '已启用' : '已禁用')
  } catch (error) {
    console.error('更新通知渠道状态失败:', error)
    channel.is_active = !channel.is_active // 回滚状态
    ElMessage.error('操作失败')
  }
}

const saveNotificationChannel = async () => {
  try {
    await notificationChannelFormRef.value.validate()

    notificationChannelDialog.loading = true

    const formData = { ...notificationChannelDialog.form }

    if (notificationChannelDialog.isEdit) {
      // 更新通知渠道
      await monitoringApi.updateNotificationChannel(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 创建新的通知渠道
      await monitoringApi.createNotificationChannel(formData)
      ElMessage.success('创建成功')
    }

    notificationChannelDialog.visible = false
    await loadNotificationChannels()
  } catch (error) {
    console.error('保存通知渠道失败:', error)
    ElMessage.error('保存失败')
  } finally {
    notificationChannelDialog.loading = false
  }
}

const updateMentionedList = () => {
  if (mentionedUsers.value) {
    notificationChannelDialog.form.config.mentioned_list = mentionedUsers.value
      .split(',')
      .map(user => user.trim())
      .filter(user => user)
  } else {
    notificationChannelDialog.form.config.mentioned_list = []
  }
}

const updateAtMobiles = () => {
  if (atMobiles.value) {
    notificationChannelDialog.form.config.at_mobiles = atMobiles.value
      .split(',')
      .map(mobile => mobile.trim())
      .filter(mobile => mobile)
  } else {
    notificationChannelDialog.form.config.at_mobiles = []
  }
}

const updateEmailRecipients = () => {
  if (emailRecipients.value) {
    notificationChannelDialog.form.config.recipients = emailRecipients.value
      .split(',')
      .map(email => email.trim())
      .filter(email => email)
  } else {
    notificationChannelDialog.form.config.recipients = []
  }
}

const acknowledgeAlert = async (alert) => {
  try {
    const { value: comment } = await ElMessageBox.prompt('请输入确认备注', '确认告警', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      inputPlaceholder: '可选：添加确认备注'
    })

    await monitoringApi.acknowledgeAlert(alert.id, {
      message: comment || ''
    })

    ElMessage.success('告警已确认')
    await refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认告警失败:', error)
      ElMessage.error('确认告警失败')
    }
  }
}

const resolveAlert = async (alert) => {
  try {
    await ElMessageBox.confirm('确定要解决这个告警吗？', '解决告警', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await monitoringApi.resolveAlert({
      alert_id: alert.id
    })

    ElMessage.success('告警已解决')
    await refreshData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解决告警失败:', error)
      ElMessage.error('解决告警失败')
    }
  }
}

// 删除告警
const deleteAlert = async (alert) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除告警 "${alert.title}" 吗？此操作不可恢复。`,
      '删除告警',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    const response = await monitoringApi.deleteAlert(alert.id)

    if (response.data && response.data.success) {
      ElMessage.success('告警已删除')
      await refreshData()
    } else {
      ElMessage.error(response.data?.message || '删除告警失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除告警失败:', error)
      ElMessage.error('删除告警失败')
    }
  }
}



// 告警规则管理
const alertRules = ref([])
const alertRuleDialog = reactive({
  visible: false,
  isEdit: false,
  title: '创建告警规则'
})

const alertRuleForm = reactive({
  id: null,
  name: '',
  description: '',
  template_id: '',
  metric_name: '',
  condition: '>',
  threshold_value: 0,
  severity: 'medium',
  duration: 300,
  zabbix_server: null,
  host_groups: [],
  enable_notification: true,
  notification_channels: [],
  is_active: true
})

const conditionOptions = [
  { label: '大于 (>)', value: '>' },
  { label: '大于等于 (>=)', value: '>=' },
  { label: '小于 (<)', value: '<' },
  { label: '小于等于 (<=)', value: '<=' },
  { label: '等于 (=)', value: '=' },
  { label: '不等于 (!=)', value: '!=' }
]

// 模板和监控项相关数据
const templateOptions = ref([])
const metricOptions = ref([])
const templatesLoading = ref(false)
const itemsLoading = ref(false)

// 模板搜索相关
const templateSearchQuery = ref('')
const selectedTemplate = ref(null)
const templateSearchResults = ref([])

// Zabbix服务器数据
const zabbixServers = ref([])

const severityOptions = [
  { label: '轻微', value: 'low' },
  { label: '一般', value: 'medium' },
  { label: '严重', value: 'high' },
  { label: '紧急', value: 'critical' }
]

const showCreateAlert = () => {
  showCreateRule()
}

const showCreateRule = async () => {
  console.log('🚀 显示创建告警规则对话框')
  alertRuleDialog.isEdit = false
  alertRuleDialog.title = '创建告警规则'
  resetAlertRuleForm()

  // 清空选项
  templateOptions.value = []
  metricOptions.value = []

  try {
    // 并行加载通知渠道和Zabbix服务器
    console.log('📡 开始并行加载通知渠道和Zabbix服务器...')
    await Promise.all([
      loadNotificationChannels(),
      loadZabbixServers()
    ])
    console.log('✅ 所有数据加载完成')
    console.log('✅ 通知渠道数量:', notificationChannels.value.length)
    console.log('✅ 激活的渠道数量:', notificationChannels.value.filter(c => c.is_active).length)
    console.log('✅ Zabbix服务器数量:', zabbixServers.value.length)
  } catch (error) {
    console.error('❌ 加载数据失败:', error)
    ElMessage.error('加载数据失败: ' + error.message)
  }

  alertRuleDialog.visible = true
}

const resetAlertRuleForm = () => {
  Object.assign(alertRuleForm, {
    id: null,
    name: '',
    description: '',
    template_id: '',
    metric_name: '',
    condition: '>',
    threshold_value: 0,
    severity: 'medium',
    duration: 300,
    zabbix_server: null,
    host_groups: [],
    enable_notification: true,
    notification_channels: [],
    is_active: true
  })

  // 清空选项
  templateOptions.value = []
  metricOptions.value = []
}

// 加载Zabbix服务器列表
const loadZabbixServers = async () => {
  try {
    const response = await monitoringApi.getZabbixServers()
    console.log('🔍 Zabbix服务器API响应:', response.data)

    if (response.data && response.data.success && response.data.data) {
      zabbixServers.value = response.data.data
      console.log('✅ 加载Zabbix服务器成功:', zabbixServers.value.length, '个')
    } else {
      console.warn('⚠️ Zabbix服务器数据格式异常:', response.data)
      zabbixServers.value = []
    }
  } catch (error) {
    console.error('❌ 获取Zabbix服务器失败:', error)
    ElMessage.error('获取Zabbix服务器失败')
    zabbixServers.value = []
  }
}



// 加载告警规则
const loadAlertRules = async () => {
  try {
    const response = await monitoringApi.getAlertRules()
    if (response.data.success !== false) {
      // 处理DRF分页格式
      if (response.data.results) {
        alertRules.value = response.data.results
      } else {
        alertRules.value = response.data
      }
    }
  } catch (error) {
    console.error('加载告警规则失败:', error)
    ElMessage.error('加载告警规则失败')
  }
}

// 保存告警规则
const saveAlertRule = async () => {
  try {
    // 验证必填字段
    if (!alertRuleForm.name) {
      ElMessage.error('请输入规则名称')
      return
    }
    if (!alertRuleForm.zabbix_server) {
      ElMessage.error('请选择Zabbix服务器')
      return
    }
    if (!alertRuleForm.metric_name) {
      ElMessage.error('请输入监控项名称')
      return
    }

    const formData = { ...alertRuleForm }

    // 移除template_id字段，后端不需要
    delete formData.template_id

    // 确保数据类型正确
    formData.threshold_value = Number(formData.threshold_value)
    formData.duration = Number(formData.duration)

    // 确保通知渠道是数字数组，过滤掉无效值
    if (formData.notification_channels && Array.isArray(formData.notification_channels)) {
      formData.notification_channels = formData.notification_channels
        .filter(id => id !== null && id !== undefined && id !== '' && id !== 'None')
        .map(id => {
          // 如果是邮件配置ID（格式为 email_123），跳过它，因为后端不支持邮件配置作为通知渠道
          if (typeof id === 'string' && id.startsWith('email_')) {
            console.warn('⚠️ 跳过邮件配置ID:', id, '（后端暂不支持邮件配置作为告警规则通知渠道）')
            return null
          }
          return Number(id)
        })
        .filter(id => id !== null && !isNaN(id))
    } else {
      formData.notification_channels = []
    }

    // 确保主机组是数字数组，过滤掉无效值
    if (formData.host_groups && Array.isArray(formData.host_groups)) {
      formData.host_groups = formData.host_groups
        .filter(id => id !== null && id !== undefined && id !== '' && id !== 'None')
        .map(id => Number(id))
        .filter(id => !isNaN(id))
    } else {
      formData.host_groups = []
    }

    console.log('📤 提交告警规则数据:', formData)
    console.log('📤 通知渠道数据:', formData.notification_channels)
    console.log('📤 主机组数据:', formData.host_groups)

    if (alertRuleDialog.isEdit) {
      console.log('📝 执行更新操作，ID:', formData.id)
      await monitoringApi.updateAlertRule(formData.id, formData)
      ElMessage.success('告警规则更新成功')
    } else {
      console.log('➕ 执行创建操作')
      await monitoringApi.createAlertRule(formData)
      ElMessage.success('告警规则创建成功')
    }

    alertRuleDialog.visible = false
    await loadAlertRules()
  } catch (error) {
    console.error('保存告警规则失败:', error)
    if (error.response && error.response.data) {
      console.error('错误详情:', error.response.data)
      ElMessage.error('保存失败: ' + (error.response.data.message || JSON.stringify(error.response.data)))
    } else {
      ElMessage.error('保存告警规则失败: ' + error.message)
    }
  }
}

// 搜索监控模板
const searchTemplates = async (queryString, callback) => {
  if (!alertRuleForm.zabbix_server) {
    callback([])
    return
  }

  if (!queryString || queryString.length < 2) {
    callback([])
    return
  }

  try {
    templatesLoading.value = true
    const response = await monitoringApi.searchTemplates(alertRuleForm.zabbix_server, queryString)
    console.log('模板搜索响应:', response.data)

    if (response.data && response.data.success && response.data.data) {
      const suggestions = response.data.data.map(template => ({
        value: template.name,
        templateid: template.templateid,
        name: template.name,
        description: template.description || ''
      }))
      callback(suggestions)
    } else {
      callback([])
    }
  } catch (error) {
    console.error('搜索模板失败:', error)
    callback([])
  } finally {
    templatesLoading.value = false
  }
}

// 选择模板
const onTemplateSelect = (item) => {
  selectedTemplate.value = item
  alertRuleForm.template_id = item.templateid
  templateSearchQuery.value = item.name

  // 加载该模板的监控项
  loadTemplateItems(item.templateid)
}

// 清除选中的模板
const clearSelectedTemplate = () => {
  selectedTemplate.value = null
  alertRuleForm.template_id = ''
  templateSearchQuery.value = ''
  metricOptions.value = []
  alertRuleForm.metric_name = ''
}

// Zabbix服务器变化处理
const onZabbixServerChange = async (serverId) => {
  if (!serverId) {
    templateOptions.value = []
    metricOptions.value = []
    alertRuleForm.template_id = ''
    alertRuleForm.metric_name = ''
    selectedTemplate.value = null
    templateSearchQuery.value = ''
    return
  }
}

// 加载模板监控项
const loadTemplateItems = async (templateId) => {
  if (!templateId) {
    metricOptions.value = []
    alertRuleForm.metric_name = ''
    return
  }

  try {
    itemsLoading.value = true
    const response = await monitoringApi.getTemplateItems(alertRuleForm.zabbix_server, templateId)
    console.log('监控项API响应:', response.data)

    if (response.data && response.data.success && response.data.data) {
      // 检查响应数据结构
      if (response.data.data.items) {
        metricOptions.value = response.data.data.items
      } else {
        metricOptions.value = response.data.data
      }
      alertRuleForm.metric_name = '' // 清空已选择的监控项
      console.log('加载的监控项:', metricOptions.value)
    } else {
      console.error('监控项API响应格式错误:', response.data)
      ElMessage.error('获取监控项失败')
    }
  } catch (error) {
    console.error('获取监控项失败:', error)
    ElMessage.error('获取监控项失败')
  } finally {
    itemsLoading.value = false
  }
}

// 编辑告警规则
const editAlertRule = (rule) => {
  alertRuleDialog.isEdit = true
  alertRuleDialog.title = '编辑告警规则'

  // 安全地复制数据，确保数组字段正确处理
  Object.assign(alertRuleForm, {
    ...rule,
    notification_channels: rule.notification_channels || [],
    host_groups: rule.host_groups || [],
    template_id: '' // 编辑时重置模板选择
  })

  console.log('📝 编辑告警规则数据:', alertRuleForm)
  alertRuleDialog.visible = true
}

// 删除告警规则
const deleteAlertRule = async (rule) => {
  try {
    await ElMessageBox.confirm(`确定要删除告警规则 "${rule.name}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await monitoringApi.deleteAlertRule(rule.id)
    ElMessage.success('告警规则删除成功')
    await loadAlertRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除告警规则失败:', error)
      ElMessage.error('删除告警规则失败')
    }
  }
}

const toggleRule = async (rule) => {
  try {
    await monitoringApi.toggleAlertRule(rule.id)
    ElMessage.success(`规则 "${rule.name}" 状态切换成功`)
    await loadAlertRules()
  } catch (error) {
    console.error('切换规则状态失败:', error)
    ElMessage.error('切换规则状态失败')
  }
}

const editRule = (rule) => {
  editAlertRule(rule)
}

const testRule = async (rule) => {
  try {
    const response = await monitoringApi.testAlertRule(rule.id)
    if (response.data.success) {
      ElMessage.success(`规则 "${rule.name}" 测试成功`)
    } else {
      ElMessage.error(response.data.message || '规则测试失败')
    }
  } catch (error) {
    console.error('测试规则失败:', error)
    ElMessage.error('测试规则失败')
  }
}

const deleteRule = async (rule) => {
  try {
    await ElMessageBox.confirm(`确定要删除告警规则 "${rule.name}" 吗？`, '删除规则', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteAlertRule(rule)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除告警规则失败:', error)
      ElMessage.error('删除告警规则失败')
    }
  }
}

// 邮件配置相关方法
const showCreateEmailConfig = () => {
  emailConfigDialog.visible = true
  emailConfigDialog.isEdit = false
  emailConfigDialog.form = {
    name: '',
    smtp_server: '',
    smtp_port: 587,
    username: '',
    password: '',
    from_email: '',
    default_recipients: '',
    encryption: 'tls',
    is_default: false,
    is_active: true
  }
}

const saveEmailConfig = async () => {
  try {
    await emailConfigFormRef.value.validate()

    emailConfigDialog.loading = true

    // 转换加密方式
    const formData = {
      ...emailConfigDialog.form,
      use_tls: emailConfigDialog.form.encryption === 'tls',
      use_ssl: emailConfigDialog.form.encryption === 'ssl'
    }
    delete formData.encryption

    // 如果是编辑模式且密码是占位符，则不发送密码字段
    if (emailConfigDialog.isEdit && formData.password === '••••••••••••') {
      delete formData.password
    }

    let response
    if (emailConfigDialog.isEdit) {
      response = await monitoringApi.updateEmailConfig(emailConfigDialog.form.id, formData)
    } else {
      response = await monitoringApi.createEmailConfig(formData)
    }

    if (response.data.id || response.data.success) {
      ElMessage.success(`邮件配置${emailConfigDialog.isEdit ? '更新' : '创建'}成功`)
      emailConfigDialog.visible = false
      await loadEmailConfigs()
    } else {
      ElMessage.error(response.data.message || `${emailConfigDialog.isEdit ? '更新' : '创建'}邮件配置失败`)
    }
  } catch (error) {
    console.error('保存邮件配置失败:', error)
    ElMessage.error('保存邮件配置失败')
  } finally {
    emailConfigDialog.loading = false
  }
}

const testEmailConfig = async (config) => {
  try {
    testingConfig.value = config.id
    const response = await monitoringApi.testEmailConfig(config.id)
    if (response.data.success) {
      ElMessage.success('测试邮件发送成功，请检查收件箱')
    } else {
      ElMessage.error(response.data.message || '测试邮件发送失败')
    }
  } catch (error) {
    console.error('测试邮件配置失败:', error)
    ElMessage.error('测试邮件配置失败')
  } finally {
    testingConfig.value = null
  }
}

const setDefaultEmailConfig = async (config) => {
  try {
    const response = await monitoringApi.setDefaultEmailConfig(config.id)
    if (response.data.success) {
      ElMessage.success('默认配置设置成功')
      await loadEmailConfigs()
    } else {
      ElMessage.error(response.data.message || '设置默认配置失败')
    }
  } catch (error) {
    console.error('设置默认配置失败:', error)
    ElMessage.error('设置默认配置失败')
  }
}

const toggleEmailConfig = async (config) => {
  try {
    const response = await monitoringApi.updateEmailConfig(config.id, {
      is_active: config.is_active
    })
    if (response.data.success || response.data.id) {
      ElMessage.success(`邮件配置已${config.is_active ? '启用' : '禁用'}`)
    } else {
      ElMessage.error('更新配置状态失败')
      config.is_active = !config.is_active // 回滚状态
    }
  } catch (error) {
    console.error('更新配置状态失败:', error)
    ElMessage.error('更新配置状态失败')
    config.is_active = !config.is_active // 回滚状态
  }
}

const editEmailConfig = (config) => {
  emailConfigDialog.visible = true
  emailConfigDialog.isEdit = true
  emailConfigDialog.form = {
    id: config.id,
    name: config.name,
    smtp_server: config.smtp_server,
    smtp_port: config.smtp_port,
    username: config.username,
    password: '••••••••••••', // 显示占位符，表示密码已保存
    from_email: config.from_email,
    default_recipients: config.default_recipients || '',
    encryption: config.use_tls ? 'tls' : (config.use_ssl ? 'ssl' : 'none'),
    is_default: config.is_default,
    is_active: config.is_active
  }
}

const deleteEmailConfig = async (config) => {
  try {
    await ElMessageBox.confirm('确定要删除这个邮件配置吗？', '删除配置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await monitoringApi.deleteEmailConfig(config.id)
    if (response.status === 204) {
      ElMessage.success('邮件配置删除成功')
      await loadEmailConfigs()
    } else {
      ElMessage.error('删除邮件配置失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除邮件配置失败:', error)
      ElMessage.error('删除邮件配置失败')
    }
  }
}

// 动态注入样式
const injectDropdownStyles = () => {
  const styleId = 'zabbix-alerts-dropdown-styles'
  if (document.getElementById(styleId)) {
    return
  }

  const style = document.createElement('style')
  style.id = styleId
  style.innerHTML = `
    .el-select-dropdown {
      background: #1a1a1a !important;
      backdrop-filter: blur(15px) !important;
      border: 1px solid rgba(164, 244, 186, 0.6) !important;
      border-radius: 12px !important;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.8) !important;
      max-height: 300px !important;
      max-width: 400px !important;
      width: auto !important;
      overflow-y: auto !important;
    }

    .el-select-dropdown__wrap {
      max-height: 280px !important;
      overflow-y: auto !important;
    }

    .el-select-dropdown__item {
      color: #ffffff !important;
      background: transparent !important;
      padding: 8px 12px !important;
      font-size: 14px !important;
      line-height: 1.4 !important;
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      font-weight: 500 !important;
    }

    .el-select-dropdown__item:hover {
      background: rgba(164, 244, 186, 0.3) !important;
      color: #000000 !important;
      font-weight: 600 !important;
    }

    .el-select-dropdown__item.selected {
      background: rgba(164, 244, 186, 0.8) !important;
      color: #000000 !important;
      font-weight: 600 !important;
    }

    .el-autocomplete-suggestion {
      background: #1a1a1a !important;
      backdrop-filter: blur(15px) !important;
      border: 1px solid rgba(164, 244, 186, 0.6) !important;
      border-radius: 12px !important;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.8) !important;
      max-height: 300px !important;
      max-width: 400px !important;
      width: auto !important;
      overflow-y: auto !important;
    }

    .el-autocomplete-suggestion__list {
      max-height: 280px !important;
      overflow-y: auto !important;
    }

    .el-autocomplete-suggestion li {
      color: #ffffff !important;
      background: transparent !important;
      padding: 10px 12px !important;
      font-size: 14px !important;
      line-height: 1.4 !important;
      border-bottom: 1px solid rgba(164, 244, 186, 0.2) !important;
      white-space: nowrap !important;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      font-weight: 500 !important;
    }

    .el-autocomplete-suggestion li:last-child {
      border-bottom: none !important;
    }

    .el-autocomplete-suggestion li:hover {
      background: rgba(164, 244, 186, 0.3) !important;
      color: #000000 !important;
      font-weight: 600 !important;
    }

    .el-autocomplete-suggestion li.highlighted {
      background: rgba(164, 244, 186, 0.8) !important;
      color: #000000 !important;
      font-weight: 600 !important;
    }
  `
  document.head.appendChild(style)
}



// 生命周期
onMounted(() => {
  refreshData()
  injectDropdownStyles()
  // 启用SSE自动连接
  initSafeSSE()
  // 加载SSE通知渠道配置
  loadSSEChannelConfig()
})

onUnmounted(() => {
  // 清理SSE连接
  cleanupSSE()
})

// 新的安全SSE功能
const initSafeSSE = () => {
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      console.warn('未找到认证token，跳过SSE连接')
      return
    }

    console.log('初始化安全SSE连接...')

    // 延迟加载SSE服务，避免阻塞页面
    setTimeout(() => {
      import('@/utils/sse').then(({ sseService }) => {
      // 设置消息处理器
      sseService.onMessage((alertData) => {
        console.log('收到新告警通知:', alertData)

        // 显示通知
        ElNotification({
          title: '新告警',
          message: `${alertData.hostname}: ${alertData.title}`,
          type: alertData.severity === 'High' ? 'error' : 'warning',
          duration: 5000
        })

        // 刷新告警列表
        refreshData()
      })

      // 设置连接状态处理器
      sseService.onConnect(() => {
        console.log('SSE连接已建立')
        // 只在首次连接时显示成功消息，避免重连时重复弹窗
        if (!sseService.hasShownConnectedMessage) {
          ElMessage.success('实时告警推送已启用')
          sseService.hasShownConnectedMessage = true
        }
      })

      sseService.onDisconnect(() => {
        console.log('SSE连接已断开')
      })

      sseService.onError((error) => {
        console.error('SSE连接错误:', error)
      })

        // 建立连接
        sseService.connect(token)
      }).catch(error => {
        console.error('加载SSE服务失败:', error)
      })
    }, 2000) // 延迟2秒加载

  } catch (error) {
    console.error('初始化SSE失败:', error)
  }
}

// SSE测试功能
const handleTestSSE = async (command) => {
  console.log('🚀 SSE测试命令:', command)

  try {
    let testData = {}

    switch (command) {
      case 'simple':
        // 简单推送测试
        testData = {
          alert_type: 'test',
          message: '这是一个简单的SSE推送测试',
          severity: 'warning',
          create_real_alert: false,
          send_notifications: false
        }
        break

      case 'real':
        // 真实告警测试
        testData = {
          alert_type: 'real_test',
          message: '这是一个真实告警创建测试',
          severity: 'high',
          create_real_alert: true,
          send_notifications: false
        }
        break

      case 'notification':
        // 通知渠道测试
        const activeChannels = notificationChannels.value.filter(c => c.is_active)
        if (activeChannels.length === 0) {
          ElMessage.warning('没有活跃的通知渠道，请先配置通知渠道')
          return
        }

        testData = {
          alert_type: 'notification_test',
          message: '这是一个通知渠道测试告警',
          severity: 'critical',
          create_real_alert: true,
          send_notifications: true,
          notification_channels: activeChannels.map(c => c.id)
        }
        break

      default:
        ElMessage.error('未知的测试类型')
        return
    }

    console.log('📤 发送SSE测试请求:', testData)

    // 发送测试请求
    const response = await monitoringApi.testAlertPush(testData)
    console.log('📥 SSE测试响应:', response.data)

    if (response.data.success) {
      ElNotification({
        title: 'SSE测试成功',
        message: response.data.message,
        type: 'success',
        duration: 5000
      })

      // 如果创建了真实告警，刷新告警列表
      if (testData.create_real_alert) {
        setTimeout(() => {
          loadAlerts()
        }, 1000)
      }

      // 显示详细结果
      if (response.data.data) {
        const data = response.data.data
        let detailMessage = `测试类型: ${command}\n`
        detailMessage += `SSE推送: ${data.sse_pushed ? '成功' : '失败'}\n`
        detailMessage += `通知发送: ${data.notifications_sent ? '是' : '否'}\n`

        if (data.notification_results && data.notification_results.length > 0) {
          detailMessage += '\n通知结果:\n'
          data.notification_results.forEach(result => {
            detailMessage += `- ${result.channel}: ${result.status} (${result.message})\n`
          })
        }

        if (data.alert_id) {
          detailMessage += `\n告警ID: ${data.alert_id}`
        }

        console.log('📊 测试详情:', detailMessage)
      }
    } else {
      ElMessage.error(response.data.message || 'SSE测试失败')
    }

  } catch (error) {
    console.error('❌ SSE测试失败:', error)
    ElMessage.error('SSE测试失败: ' + (error.response?.data?.message || error.message))
  }
}

// SSE通知配置相关方法
const toggleSSEChannel = (channelId) => {
  const index = sseSelectedChannels.value.indexOf(channelId)
  if (index > -1) {
    sseSelectedChannels.value.splice(index, 1)
  } else {
    sseSelectedChannels.value.push(channelId)
  }
}



const testSSENotification = async () => {
  if (sseSelectedChannels.value.length === 0) {
    ElMessage.warning('请先选择要测试的通知渠道')
    return
  }

  testingSSENotification.value = true
  try {
    const testData = {
      mode: 'notification',
      notification_channels: sseSelectedChannels.value
    }

    const response = await monitoringApi.testAlertPush(testData)
    if (response.data.success) {
      ElNotification({
        title: 'SSE通知测试成功',
        message: `已向 ${sseSelectedChannels.value.length} 个渠道发送测试通知`,
        type: 'success',
        duration: 5000
      })
    } else {
      ElMessage.error(response.data.message || 'SSE通知测试失败')
    }
  } catch (error) {
    console.error('SSE通知测试失败:', error)
    ElMessage.error('SSE通知测试失败: ' + (error.response?.data?.message || error.message))
  } finally {
    testingSSENotification.value = false
  }
}

const saveSSEChannelConfig = async () => {
  savingSSEConfig.value = true
  try {
    const response = await monitoringApi.saveSSEConfig({
      notification_channels: sseSelectedChannels.value
    })

    if (response.data.success) {
      ElNotification({
        title: '配置保存成功',
        message: response.data.message,
        type: 'success',
        duration: 3000
      })

      showSSEChannelConfig.value = false
    } else {
      ElMessage.error(response.data.message || '保存SSE配置失败')
    }
  } catch (error) {
    console.error('保存SSE配置失败:', error)
    ElMessage.error('保存SSE配置失败: ' + (error.response?.data?.message || error.message))
  } finally {
    savingSSEConfig.value = false
  }
}

const loadSSEChannelConfig = async () => {
  try {
    const response = await monitoringApi.getSSEConfig()
    if (response.data.success) {
      sseSelectedChannels.value = response.data.data.notification_channels || []
    }
  } catch (error) {
    console.error('加载SSE配置失败:', error)
    // 如果API失败，尝试从localStorage加载作为备用
    try {
      const saved = localStorage.getItem('sse_notification_channels')
      if (saved) {
        sseSelectedChannels.value = JSON.parse(saved)
      }
    } catch (localError) {
      console.error('从localStorage加载SSE配置也失败:', localError)
    }
  }
}

const cleanupSSE = () => {
  try {
    import('@/utils/sse').then(({ sseService }) => {
      sseService.disconnect()
      console.log('SSE连接已清理')
    })
  } catch (error) {
    console.error('清理SSE连接失败:', error)
  }
}
</script>

<style scoped>
/* 复用相同的基础样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, rgba(0, 0, 0, 0.9) 0%, rgba(20, 20, 40, 0.95) 50%, rgba(0, 0, 0, 0.9) 100%);
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite;
  opacity: 0.6;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 25px, rgba(255,255,255,0.9), transparent);
  background-repeat: repeat;
  background-size: 300px 150px;
  animation: zoom 40s infinite;
  opacity: 0.4;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, #fff, transparent),
    radial-gradient(1px 1px at 150px 150px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 400px 200px;
  animation: zoom 60s infinite;
  opacity: 0.3;
}

@keyframes zoom {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.content-wrapper {
  position: relative;
  z-index: 1;
  padding: 20px 20px 100px 20px; /* 增加底部padding避免被footer遮挡 */
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  box-shadow:
    0 4px 16px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  padding: 24px;
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section h1 {
  color: #00eaff;
  margin: 0 0 8px 0;
  font-size: 2rem;
  font-weight: 600;
}

.title-section p {
  color: rgba(255, 255, 255, 0.7);
  margin: 0;
  font-size: 1rem;
}

.action-section {
  display: flex;
  gap: 12px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
}

.stat-icon.critical {
  background: rgba(220, 38, 127, 0.2);
  color: #dc2626;
}

.stat-icon.high {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.stat-icon.medium {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.stat-icon.low {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1;
}

.stat-label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.9rem;
  margin-top: 4px;
}

.alerts-section, .rules-section, .notification-section {
  padding: 24px;
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #00eaff;
  margin: 0;
  font-size: 1.3rem;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.alerts-list, .rules-list, .email-configs-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.alert-card, .rule-card, .config-card {
  padding: 20px;
  border-left: 4px solid rgba(164, 244, 186, 0.5);
}

.alert-card.severity-critical {
  border-left-color: #dc2626;
}

.alert-card.severity-high {
  border-left-color: #ef4444;
}

.alert-card.severity-medium {
  border-left-color: #f59e0b;
}

.alert-card.severity-low {
  border-left-color: #3b82f6;
}

.alert-header, .rule-header, .config-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.alert-info h4, .rule-info h4, .config-info h4 {
  color: rgba(255, 255, 255, 0.9);
  margin: 0 0 4px 0;
  font-size: 1.1rem;
}

.alert-host, .rule-metric, .config-server {
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.9rem;
}

.alert-meta {
  display: flex;
  gap: 8px;
}

.severity-badge, .status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: 500;
}

.severity-badge.severity-critical {
  background: rgba(220, 38, 127, 0.2);
  color: #dc2626;
}

.severity-badge.severity-high {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.severity-badge.severity-medium {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.severity-badge.severity-low {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
}

.status-badge.status-active {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.status-badge.status-acknowledged {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.status-badge.status-resolved {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
}

.alert-description {
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 12px;
  font-size: 0.9rem;
}

.alert-details, .config-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
  margin-bottom: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-item .label {
  color: rgba(255, 255, 255, 0.7);
  font-size: 0.8rem;
}

.detail-item .value {
  color: rgba(255, 255, 255, 0.9);
  font-size: 0.8rem;
  font-weight: 500;
}

.rule-condition {
  margin-bottom: 16px;
}

.condition-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 0.9rem;
  font-style: italic;
}

.alert-actions, .rule-actions, .config-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.action-btn {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  padding: 10px 20px !important;
  border-radius: 8px !important;
  cursor: pointer !important;
  transition: all 0.3s ease !important;
  font-size: 13px !important;
  min-width: 85px !important;
  height: 36px !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  gap: 6px !important;
  white-space: nowrap !important;
  font-weight: 500 !important;
  line-height: 1 !important;
}

.action-btn:hover {
  background: rgba(164, 244, 186, 0.25);
  border-color: rgba(164, 244, 186, 0.5);
}

/* 测试按钮 - 蓝色 */
.action-btn.test {
  background: rgba(59, 130, 246, 0.2) !important;
  border-color: rgba(59, 130, 246, 0.4) !important;
  color: #3b82f6 !important;
}

.action-btn.test:hover {
  background: rgba(59, 130, 246, 0.3) !important;
  border-color: rgba(59, 130, 246, 0.6) !important;
}

/* 设为默认按钮 - 紫色 */
.action-btn.default {
  background: rgba(147, 51, 234, 0.2) !important;
  border-color: rgba(147, 51, 234, 0.4) !important;
  color: #9333ea !important;
}

.action-btn.default:hover {
  background: rgba(147, 51, 234, 0.3) !important;
  border-color: rgba(147, 51, 234, 0.6) !important;
}

/* 编辑按钮 - 橙色 */
.action-btn.edit {
  background: rgba(245, 158, 11, 0.2) !important;
  border-color: rgba(245, 158, 11, 0.4) !important;
  color: #f59e0b !important;
}

.action-btn.edit:hover {
  background: rgba(245, 158, 11, 0.3) !important;
  border-color: rgba(245, 158, 11, 0.6) !important;
}

/* 删除按钮 - 红色 */
.action-btn.delete {
  background: rgba(239, 68, 68, 0.2) !important;
  border-color: rgba(239, 68, 68, 0.4) !important;
  color: #ef4444 !important;
}

.action-btn.delete:hover {
  background: rgba(239, 68, 68, 0.3) !important;
  border-color: rgba(239, 68, 68, 0.6) !important;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

/* 通知配置表格样式 */
.notification-configs-table {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.2);
  overflow: hidden;
  width: 100%;
}

.table-header {
  display: grid !important;
  grid-template-columns: 1.2fr 1fr 1.5fr 1.5fr 0.8fr 2fr !important;
  background: rgba(164, 244, 186, 0.1);
  border-bottom: 1px solid rgba(164, 244, 186, 0.3);
  padding: 0;
}

.header-cell {
  padding: 15px 8px;
  font-weight: 600;
  color: #a4f4ba;
  font-size: 13px;
  text-align: center;
  border-right: 1px solid rgba(164, 244, 186, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-cell:last-child {
  border-right: none;
}

.table-row {
  display: grid !important;
  grid-template-columns: 1.2fr 1fr 1.5fr 1.5fr 0.8fr 2fr !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1);
  transition: all 0.3s ease;
}

.table-row:hover {
  background: rgba(164, 244, 186, 0.05);
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  padding: 15px 8px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 13px;
  border-right: 1px solid rgba(164, 244, 186, 0.1);
  display: flex;
  align-items: center;
  min-height: 60px;
  word-wrap: break-word;
  overflow: hidden;
}



.table-cell:last-child {
  border-right: none;
  overflow: visible;
}

.table-cell.name {
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  gap: 4px;
}

.config-name {
  font-weight: 500;
  display: block;
}

.default-badge {
  background: rgba(147, 51, 234, 0.3);
  color: #9333ea;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
}

.recipients-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  max-width: 100%;
}

.recipient-tag {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 11px;
  white-space: nowrap;
  font-weight: 500;
  border: 1px solid;
}

/* 收件人标签配色 - 6种颜色循环 */
.recipient-tag.recipient-0 {
  background: rgba(164, 244, 186, 0.2);
  border-color: rgba(164, 244, 186, 0.5);
  color: #a4f4ba;
}

.recipient-tag.recipient-1 {
  background: rgba(59, 130, 246, 0.2);
  border-color: rgba(59, 130, 246, 0.5);
  color: #3b82f6;
}

.recipient-tag.recipient-2 {
  background: rgba(245, 158, 11, 0.2);
  border-color: rgba(245, 158, 11, 0.5);
  color: #f59e0b;
}

.recipient-tag.recipient-3 {
  background: rgba(239, 68, 68, 0.2);
  border-color: rgba(239, 68, 68, 0.5);
  color: #ef4444;
}

.recipient-tag.recipient-4 {
  background: rgba(147, 51, 234, 0.2);
  border-color: rgba(147, 51, 234, 0.5);
  color: #9333ea;
}

.recipient-tag.recipient-5 {
  background: rgba(34, 197, 94, 0.2);
  border-color: rgba(34, 197, 94, 0.5);
  color: #22c55e;
}

.no-recipients {
  color: rgba(255, 255, 255, 0.5);
  font-style: italic;
}

.encryption-badge {
  background: rgba(59, 130, 246, 0.2);
  border: 1px solid rgba(59, 130, 246, 0.4);
  color: #3b82f6;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
  align-items: center;
}

.default-action {
  display: flex;
  justify-content: center;
}

.main-actions {
  display: flex;
  gap: 6px;
  justify-content: center;
}

.action-btn.acknowledge {
  background: rgba(245, 158, 11, 0.2);
  border-color: rgba(245, 158, 11, 0.4);
  color: #f59e0b;
}

.action-btn.resolve {
  background: rgba(34, 197, 94, 0.2);
  border-color: rgba(34, 197, 94, 0.4);
  color: #22c55e;
}

.action-btn.delete {
  background: rgba(244, 67, 54, 0.2);
  border-color: rgba(244, 67, 54, 0.4);
  color: #f44336;
}

.action-btn.delete:hover {
  background: rgba(244, 67, 54, 0.3);
  border-color: rgba(244, 67, 54, 0.6);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.empty-state i {
  font-size: 4rem;
  margin-bottom: 16px;
  color: rgba(164, 244, 186, 0.3);
}

.empty-state h3 {
  margin: 0 0 8px 0;
  color: rgba(255, 255, 255, 0.8);
}

/* 邮件配置特有样式 */
.config-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.default-badge {
  background: rgba(34, 197, 94, 0.2);
  color: #22c55e;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: 500;
  border: 1px solid rgba(34, 197, 94, 0.3);
}

/* 对话框样式 */
:deep(.glass-dialog) {
  .el-dialog {
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(20px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 12px;
  }

  .el-dialog__header {
    background: rgba(164, 244, 186, 0.1);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 12px 12px 0 0;
  }

  .el-dialog__title {
    color: rgba(255, 255, 255, 0.9);
    font-weight: 600;
  }

  .el-dialog__body {
    background: rgba(255, 255, 255, 0.05);
  }

  .el-form-item__label {
    color: rgba(255, 255, 255, 0.8);
  }

  .el-input__wrapper {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
  }

  .el-input__inner {
    color: rgba(255, 255, 255, 0.9);
    background: transparent;
  }

  .el-input__inner::placeholder {
    color: rgba(255, 255, 255, 0.5);
  }
}

/* 按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 6px !important;
    color: #00eaff !important;
  }
}

.refresh-button {
  background: rgba(138, 43, 226, 0.2) !important;
  border-color: rgba(138, 43, 226, 0.4) !important;

  &:hover {
    background: rgba(138, 43, 226, 0.3) !important;
    border-color: rgba(138, 43, 226, 0.6) !important;
    box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
  }

  i {
    color: #8a2be2 !important;
  }
}

.add-button {
  background: rgba(34, 197, 94, 0.2) !important;
  border-color: rgba(34, 197, 94, 0.4) !important;

  &:hover {
    background: rgba(34, 197, 94, 0.3) !important;
    border-color: rgba(34, 197, 94, 0.6) !important;
    box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
  }

  i {
    color: #22c55e !important;
  }
}

/* 通知类型标签样式 */
.type-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(164, 244, 186, 0.3);
}

.type-badge.type-email {
  background: rgba(59, 130, 246, 0.15);
  color: #60a5fa;
  border-color: rgba(59, 130, 246, 0.3);
}

.type-badge.type-wechat {
  background: rgba(34, 197, 94, 0.15);
  color: #4ade80;
  border-color: rgba(34, 197, 94, 0.3);
}

.type-badge.type-dingtalk {
  background: rgba(249, 115, 22, 0.15);
  color: #fb923c;
  border-color: rgba(249, 115, 22, 0.3);
}

.config-info {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.8);
}

/* 表单帮助文本 */
.form-help {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
  margin-top: 4px;
  line-height: 1.4;
}

/* 下拉菜单样式调整 */
.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-actions .glass-button {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 下拉菜单透明样式 - 全局覆盖 */
.el-dropdown-menu {
  background: rgba(255, 255, 255, 0.05) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}

.el-dropdown-menu__item {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  transition: all 0.3s ease !important;
}

.el-dropdown-menu__item:hover {
  background: rgba(164, 244, 186, 0.1) !important;
  color: #a4f4ba !important;
}

.el-dropdown-menu__item i {
  color: #a4f4ba !important;
  margin-right: 8px !important;
}

/* 更强的样式覆盖 */
:deep(.el-dropdown-menu) {
  background: rgba(255, 255, 255, 0.05) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-dropdown-menu__item) {
  color: rgba(255, 255, 255, 0.9) !important;
  background: transparent !important;
  transition: all 0.3s ease !important;
}

:deep(.el-dropdown-menu__item:hover) {
  background: rgba(164, 244, 186, 0.1) !important;
  color: #a4f4ba !important;
}

:deep(.el-dropdown-menu__item i) {
  color: #a4f4ba !important;
  margin-right: 8px !important;
}

/* 选择框透明样式 */
:deep(.el-select .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.05) !important;
  backdrop-filter: blur(10px) !important;
  border: 1px solid rgba(164, 244, 186, 0.2) !important;
  border-radius: 8px !important;
}

:deep(.el-select-dropdown) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

:deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 8px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
}

:deep(.el-select-dropdown__item:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

:deep(.el-select-dropdown__item.selected) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
}

/* 批量操作样式 */
.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  margin-bottom: 20px;
  border-radius: 12px;
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
}

.batch-info {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.batch-buttons .action-btn {
  padding: 8px 16px;
  font-size: 14px;
}

.batch-buttons .action-btn.acknowledge {
  background: linear-gradient(135deg, #ffa502, #ff6348);
}

.batch-buttons .action-btn.resolve {
  background: linear-gradient(135deg, #2ed573, #1e90ff);
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  background: transparent;
}

.pagination-wrapper :deep(.el-pagination .el-pager li) {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: rgba(255, 255, 255, 0.8);
  margin: 0 2px;
  border-radius: 6px;
}

.pagination-wrapper :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #a4f4ba, #7bed9f);
  color: #2c3e50;
  font-weight: bold;
}

.pagination-wrapper :deep(.el-pagination .btn-prev),
.pagination-wrapper :deep(.el-pagination .btn-next) {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
}

/* 告警详情对话框样式 */
.alert-detail-content {
  color: rgba(255, 255, 255, 0.9);
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  color: #a4f4ba;
  margin-bottom: 16px;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.detail-item .label {
  min-width: 100px;
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
}

.detail-item .value {
  color: rgba(255, 255, 255, 0.9);
  margin-left: 12px;
}

.severity-badge,
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.description-content {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  padding: 16px;
  white-space: pre-wrap;
  word-break: break-word;
}

.json-content {
  background: rgba(0, 0, 0, 0.3);
  border: 1px solid rgba(164, 244, 186, 0.3);
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
}

.json-content pre {
  margin: 0;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  line-height: 1.4;
}

/* 图表容器样式 */
.chart-container {
  background: rgba(164, 244, 186, 0.05);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  padding: 20px;
}

/* 复选框样式 */
.alert-checkbox {
  position: absolute;
  top: 15px;
  left: 15px;
  z-index: 10;
}

.alert-card {
  position: relative;
  padding-left: 50px;
}

.alert-checkbox :deep(.el-checkbox__inner) {
  background: rgba(164, 244, 186, 0.1);
  border-color: rgba(164, 244, 186, 0.5);
}

.alert-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background: #a4f4ba;
  border-color: #a4f4ba;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  margin: 16px 0 8px;
  font-size: 18px;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
  opacity: 0.7;
}

/* 改善条件选择框和阈值输入框样式 */
.condition-select-dropdown {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

/* 阈值输入框 - 透明玻璃效果 */
.threshold-input :deep(.el-input__wrapper) {
  background: transparent !important;
  backdrop-filter: blur(15px) !important;
  border: 2px solid rgba(164, 244, 186, 0.6) !important;
  border-radius: 8px !important;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.1) !important;
  height: 40px !important;
}

.threshold-input :deep(.el-input__inner) {
  font-size: 16px !important;
  font-weight: bold !important;
  color: #ffffff !important;
  text-align: center !important;
  background: transparent !important;
  border: none !important;
  padding: 0 12px !important;
  box-shadow: none !important;
}

.threshold-input :deep(.el-input__wrapper):hover {
  border-color: rgba(164, 244, 186, 0.8) !important;
  background: rgba(164, 244, 186, 0.05) !important;
}

.threshold-input :deep(.el-input__wrapper.is-focus) {
  border-color: rgba(164, 244, 186, 1) !important;
  background: rgba(164, 244, 186, 0.1) !important;
  box-shadow: 0 0 0 2px rgba(164, 244, 186, 0.2), inset 0 2px 8px rgba(0, 0, 0, 0.1) !important;
}

/* 强制覆盖所有可能的白色背景 */
.threshold-input :deep(.el-input__inner),
.threshold-input :deep(.el-input__inner:hover),
.threshold-input :deep(.el-input__inner:focus),
.threshold-input :deep(.el-input__inner:active) {
  background: transparent !important;
  background-color: transparent !important;
}

/* 模板搜索样式 */
.template-item {
  padding: 8px 0;
}

.template-name {
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 4px;
}

.template-desc {
  font-size: 12px;
  color: #64748b;
  line-height: 1.4;
}

.selected-template {
  margin-top: 8px;
}

.selected-template .el-tag {
  background: rgba(164, 244, 186, 0.2);
  border-color: rgba(164, 244, 186, 0.5);
  color: #059669;
}



/* 表单帮助文本样式 */
.form-help {
  margin-top: 5px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  line-height: 1.4;
  background: rgba(164, 244, 186, 0.1);
  padding: 6px 10px;
  border-radius: 4px;
  border-left: 3px solid rgba(164, 244, 186, 0.5);
}

/* 自动完成下拉菜单样式 */
:deep(.el-autocomplete-suggestion) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

:deep(.el-autocomplete-suggestion__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

:deep(.el-autocomplete-suggestion li) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 10px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
}

:deep(.el-autocomplete-suggestion li:last-child) {
  border-bottom: none !important;
}

:deep(.el-autocomplete-suggestion li:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

:deep(.el-autocomplete-suggestion li.highlighted) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
}

/* 强制覆盖选择框下拉菜单样式 */
:deep(.el-select-dropdown.el-popper) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

:deep(.el-select-dropdown.el-popper .el-select-dropdown__wrap) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

:deep(.el-select-dropdown.el-popper .el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 8px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
}

:deep(.el-select-dropdown.el-popper .el-select-dropdown__item:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

:deep(.el-select-dropdown.el-popper .el-select-dropdown__item.selected) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
}

/* 强制覆盖自动完成下拉菜单样式 */
:deep(.el-autocomplete-suggestion.el-popper) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

:deep(.el-autocomplete-suggestion.el-popper .el-autocomplete-suggestion__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

:deep(.el-autocomplete-suggestion.el-popper li) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 10px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
}

:deep(.el-autocomplete-suggestion.el-popper li:last-child) {
  border-bottom: none !important;
}

:deep(.el-autocomplete-suggestion.el-popper li:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

:deep(.el-autocomplete-suggestion.el-popper li.highlighted) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
}

/* 使用更高优先级的选择器强制覆盖 */
.zabbix-alerts-container :deep(.el-select-dropdown) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

.zabbix-alerts-container :deep(.el-select-dropdown__wrap) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

.zabbix-alerts-container :deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 8px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
}

.zabbix-alerts-container :deep(.el-select-dropdown__item:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

.zabbix-alerts-container :deep(.el-select-dropdown__item.selected) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  overflow-y: auto !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion li) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 10px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion li:last-child) {
  border-bottom: none !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion li:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

.zabbix-alerts-container :deep(.el-autocomplete-suggestion li.highlighted) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
}

/* 使用ID选择器 - 最高优先级 */
#zabbix-alerts-page :deep(.el-select-dropdown) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  max-width: 400px !important;
  width: auto !important;
  overflow-y: auto !important;
}

#zabbix-alerts-page :deep(.el-select-dropdown__wrap) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

#zabbix-alerts-page :deep(.el-select-dropdown__item) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 8px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
}

#zabbix-alerts-page :deep(.el-select-dropdown__item:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

#zabbix-alerts-page :deep(.el-select-dropdown__item.selected) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
  font-weight: 500 !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion) {
  background: rgba(0, 0, 0, 0.95) !important;
  backdrop-filter: blur(15px) !important;
  border: 1px solid rgba(164, 244, 186, 0.4) !important;
  border-radius: 12px !important;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;
  max-height: 300px !important;
  max-width: 400px !important;
  width: auto !important;
  overflow-y: auto !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion__list) {
  max-height: 280px !important;
  overflow-y: auto !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion li) {
  color: rgba(255, 255, 255, 0.95) !important;
  background: transparent !important;
  padding: 10px 12px !important;
  font-size: 14px !important;
  line-height: 1.4 !important;
  border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion li:last-child) {
  border-bottom: none !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion li:hover) {
  background: rgba(164, 244, 186, 0.15) !important;
  color: #ffffff !important;
}

#zabbix-alerts-page :deep(.el-autocomplete-suggestion li.highlighted) {
  background: rgba(164, 244, 186, 0.25) !important;
  color: #ffffff !important;
}

/* SSE通知配置对话框样式 */
.sse-config-content {
  padding: 20px 0;
}

.config-description {
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.config-description p {
  margin: 0;
  color: #e0e0e0;
  line-height: 1.6;
}

.channel-selection h4 {
  margin: 0 0 15px 0;
  color: #ffffff;
  font-size: 16px;
  font-weight: 600;
}

.channel-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.2);
}

.channel-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  cursor: pointer;
  transition: all 0.3s ease;
}

.channel-item:last-child {
  border-bottom: none;
}

.channel-item:hover {
  background: rgba(255, 255, 255, 0.05);
}

.channel-item.selected {
  background: rgba(164, 244, 186, 0.15);
  border-color: rgba(164, 244, 186, 0.3);
}

.channel-info {
  flex: 1;
}

.channel-name {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #ffffff;
  font-weight: 500;
  margin-bottom: 5px;
}

.channel-name i {
  width: 16px;
  text-align: center;
}

.channel-type {
  color: #b0b0b0;
  font-size: 12px;
  margin-bottom: 3px;
}

.channel-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(255, 0, 0, 0.2);
  color: #ff6b6b;
  display: inline-block;
}

.channel-status.active {
  background: rgba(0, 255, 0, 0.2);
  color: #51cf66;
}

.channel-checkbox {
  width: 24px;
  height: 24px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.channel-item.selected .channel-checkbox {
  background: rgba(164, 244, 186, 0.8);
  border-color: #a4f4ba;
  color: #000000;
}

.config-actions {
  margin-top: 20px;
  text-align: center;
}

.config-button {
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
  color: #ffffff !important;
  padding: 8px 16px !important;
  border-radius: 6px !important;
  transition: all 0.3s ease !important;
  margin-left: 10px !important;
}

.config-button:hover {
  background: rgba(255, 255, 255, 0.15) !important;
  border-color: rgba(255, 255, 255, 0.3) !important;
  transform: translateY(-1px) !important;
}
</style>
